package com.xl.rentkeeper.business;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.xl.fuse.protos.account.CheckVerCodeReq;
import com.xl.fuse.protos.account.GetVerCodeReq;
import com.xl.fuse.protos.account.LoginReq;
import com.xl.fuse.protos.account.LoginResp;
import com.xl.fuse.protos.account.RegisterReq;
import com.xl.fuse.protos.account.RegisterResp;
import com.xl.fuse.protos.account.Session;
import com.xl.fuse.protos.account.SettingPasswordReq;
import com.xl.fuse.protos.account.SettingPasswordResp;
import com.xl.fuse.protos.account.SettingUserInfoReq;
import com.xl.fuse.protos.account.User;
import com.xl.fuse.protos.packet.Packet;
import com.xl.rentkeeper.App;
import com.xl.rentkeeper.act.LoginAct;
import com.xl.rentkeeper.db.orm.DBContext;
import com.xl.rentkeeper.db.orm.DBInterface;
import com.xl.rentkeeper.log.QLog;
import com.xl.rentkeeper.mgr.ThreadManager;
import com.xl.rentkeeper.mgr.UiObserverManager;
import com.xl.rentkeeper.net.NetEngine;
import com.xl.rentkeeper.net.Request;
import com.xl.rentkeeper.util.AndroidUtil;
import com.xl.rentkeeper.util.ErrString;

/**
 * Created by zjm on 2015/6/24.
 */
public class UserLogic extends BaseLogic {
    private static UserLogic sIns;
    public static UserLogic getInstance() {
        if (sIns == null) {
            synchronized (UserLogic.class) {
                if (sIns == null) {
                    sIns = new UserLogic();
                }
            }
        }
        return  sIns;
    }

    private static final String SWITCH_REASON_APPSTART = "appStart";
    private static final String SWITCH_REASON_LOGOUT = "logout";
    private static final String SWITCH_REASON_LOGIN = "login";
    //存储用户信息的sp
    public SharedPreferences getSp() {
        long user = getUid();
        String spKey = "user_"+user;
        return App.getApp().getSharedPreferences(spKey, Context.MODE_PRIVATE);
    }
    private UserLogic() {
        SecurityLogic.getInstance(); // load session info
        switchToNewSession(SecurityLogic.getInstance().getSession(),SWITCH_REASON_APPSTART);
    }

    private DBContext dbContext;

    public User getUser() {
        Session session = SecurityLogic.getInstance().getSession();
        if (session != null)
            return session.user;
        return null;
    }

    public long getUid() {
        User user = getUser();
        if (user != null)
            return user.uin;
        return 0;
    }

    public boolean isLogin() {
        return getUid() > 0;
    }


    public void login(User user) {
        if (user == null)
            return;
        LoginReq req = new LoginReq.Builder().user(user).build();
        // 允许网络模块启动
        NetEngine.getInstance().start();
        sendReq(0, CMD_USER_LOGIN,req,null);
    }
    public void getVerCode(User user){
        if (user == null)
            return;
        GetVerCodeReq req = new GetVerCodeReq.Builder().user(user).build();
        sendReq(0, CMD_USER_GET_CODE,req,null);
    }

    public void settingUserInfo(User user){
        if (user == null)
            return;
        SettingUserInfoReq req = new SettingUserInfoReq.Builder().user(user).build();
        sendReq(0,CMD_USER_SET_INFO,req,null);
    }

    public void settingPassword(User user){
        if (user == null)
            return;
        SettingPasswordReq req = new SettingPasswordReq.Builder().user(user).build();
        sendReq(0, CMD_USER_SET_PASS,req,null);
    }
    public void checkVerCode(User user,String vercode){
        if (user == null)
            return;
        CheckVerCodeReq req = new CheckVerCodeReq.Builder().user(user).code(vercode).build();
        sendReq(0, CMD_USER_CHECK_CODE,req,null);
    }
    public void userInfo(User user) {
        if (user == null)
            return;
        sendReq(getUid(), CMD_USER_GET_INFO,user,null);
    }

    public void register(User user,String code) {
        if (user == null || TextUtils.isEmpty(code)) {
            return;
        }
        RegisterReq req = new RegisterReq.Builder().user(user).code(code).build();
//        sendReq(0,Cmd.Account.getValue(),SubCmd.REGISTER.getValue(),req,null);
    }

    @Override
    public void onResp(Request req, Packet resp) {
        super.onResp(req, resp);
        Packet packet = req.packet;
        String cmd = packet.cmd;
        if (CMD_USER_LOGIN.equals(cmd)) {
            onLoginResp(req,resp);
        } else if (CMD_USER_REG.equals(cmd)) {
            onRegisterResp(req,resp);
        }
        else if (CMD_USER_GET_INFO.equals(cmd)) {
            User user = getResp(packet,User.class);
            showToast("user info " + resp + " user " + user);
        }else if(CMD_USER_GET_CODE.equals(cmd)){
            onGetVerCodeResp(req, resp);
        }else if(CMD_USER_CHECK_CODE.equals(cmd)){
            onCheckVerCodeResp(req, resp);
        }else if(CMD_USER_SET_PASS.equals(cmd)){
            onSettingPasswordResp(req, resp);
        }else if(CMD_USER_SET_INFO.equals(cmd)){
            onSettingUserinfoResp(req, resp);
        }
    }
    public void onSettingUserinfoResp(Request req, Packet resp){
        if(resp.ret != 0){
            App.showToast(ErrString.getErrTip(resp.ret));
        }
        UiObserverManager.getInstance().dispatchEvent(resp.cmd,resp.ret == 0,resp.error,null);
    }
    public void onSettingPasswordResp(Request req, Packet resp){
        if(resp.ret != 0){
            App.showToast(ErrString.getErrTip(resp.ret));
        }
        User user= null;
        if(resp.ret == 0){
            SettingPasswordResp spResp = getResp(resp,SettingPasswordResp.class);
            if(spResp!=null){
                user = spResp.user;
            }
        }
        UiObserverManager.getInstance().dispatchEvent(resp.cmd,resp.ret == 0,resp.error,new Object[]{user});
    }
    public void onGetVerCodeResp(Request req, Packet resp){
        if(resp.ret != 0){
            App.showToast(ErrString.getErrTip(resp.ret));
        }
        UiObserverManager.getInstance().dispatchEvent(resp.cmd,resp.ret == 0,resp.error,null);
    }
    public void onCheckVerCodeResp(Request req, Packet resp){
        UiObserverManager.getInstance().dispatchEvent(resp.cmd,resp.ret == 0,resp.error,new Object[]{resp});
    }
    public void onLoginResp(Request req, Packet resp) {
        Packet packet = resp;
        if (packet.ret == 0) {
            LoginResp loginResp = getResp(packet,LoginResp.class);
            if (loginResp != null) {
                QLog.d(this, "resp " + loginResp);
                switchToNewSession(loginResp.session,SWITCH_REASON_LOGIN);
            }
        } else {

        }
//        showToast("login isSuccess=" + (packet.ret == 0));
        UiObserverManager.getInstance().dispatchEvent(resp.cmd, packet.ret == 0, resp.error,new Object[]{resp.ret});
    }

    public void onRegisterResp(Request req, Packet resp) {
        Packet packet = resp;
        if (packet.ret == 0) {
            RegisterResp registerResp = getResp(packet,RegisterResp.class);
            if (registerResp != null) {
                SecurityLogic.getInstance().saveSessionInfo(registerResp.session);
            }
        }
        UiObserverManager.getInstance().dispatchEvent(resp.cmd, packet.ret == 0,resp.error, null);
    }

    public void logoutAndStart(String reason) {
        switchToNewSession(null, SWITCH_REASON_LOGOUT);
        UiObserverManager.getInstance().dispatchEvent(LocalCmdConst.CmdLogout,true,null,null);
        if(App.getApp().isForeground()){
            startLogin();
            if ("kick".equals(reason)) {
                App.showToast("您的账户在其他设备登录了");
            }
        }else{
            QLog.d("logoutAndStart", "not is Foreground");
            if ("kick".equals(reason)) {
                Intent intent = new Intent(App.getApp(), LoginAct.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                App.getApp().showNotification("小螺管家", "您的账户在其他设备登录了", 10, intent);
            }
        }
    }


    void startLogin() {
        Intent in = new Intent(App.getApp(), LoginAct.class);
        in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        App.getApp().startActivity(in);
    }

    synchronized void switchToNewSession(Session session,String reason) {
        QLog.d(this,"switchToNewSession  "+session+" reason:"+reason);
        if (SWITCH_REASON_APPSTART.equals(reason)) {
            if (getUid() > 0) {
                NetEngine.getInstance().start();
                ThreadManager.getInstance().runOnWorkerThread(new Runnable() {
                    @Override
                    public void run() {
                        MsgLogic.getInstance().pullMsg();
                    }
                }, 0);
            }
        } else if (SWITCH_REASON_LOGOUT.equals(reason)) {
            Session newSession = null;
            if (session != null) {
                newSession = new Session.Builder(session).imei(AndroidUtil.getIMEI(App.getApp())).build();
            }
            SecurityLogic.getInstance().saveSessionInfo(newSession);
            SingletonRegistry.clearAllInstances();
            NetEngine.getInstance().shutdown();
        } else if (SWITCH_REASON_LOGIN.equals(reason)){ // "loginResp"
            Session newSession = null;
            if (session != null) {
                newSession = new Session.Builder(session).imei(AndroidUtil.getIMEI(App.getApp())).build();
            }
            SecurityLogic.getInstance().saveSessionInfo(newSession);
            SingletonRegistry.clearAllInstances();
            if (getUid() > 0) {
                ThreadManager.getInstance().runOnWorkerThread(new Runnable() {
                    @Override
                    public void run() {
                        MsgLogic.getInstance().pullMsg();
                    }
                }, 0);
            }
        }
        if (dbContext != null) {
            dbContext.close();
        }
        dbContext = new DBContext(App.getApp(),getUid());
    }


    public DBInterface getDBInterface() {
        return dbContext.getDbInterface();
    }
}
